import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { switchMap } from 'rxjs/operators';
import { Subscription, Subject } from 'rxjs';

@Component({
  selector: 'app-switch-map-use',
  templateUrl: './switch-map-use.component.html',
  styleUrls: ['./switch-map-use.component.less'],
})
export class SwitchMapUseComponent implements OnInit {
  params = {
    page: 1,
    size: 10,
  };
  listOfData = [];
  delayTime;

  // 相关代码-定义变量
  private searchTerms = new Subject<any>();
  private searchSubscription: Subscription | undefined;

  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
    this.getNetwork();
  }

  // 相关代码-生命周期取消订阅
  ngOnDestroy(): void {
    this.unsubscribeSearch();
  }

  getNetwork() {
    let time = Math.random() * 10000;
    this.delayTime = time;
    let url = 'http://localhost:8080/api/mockDataNodePaging';
    let queryParams = new HttpParams();
    Object.keys(this.params).forEach((key) => {
      queryParams = queryParams.append(key, this.params[key]);
    });
    setTimeout(() => {
      this.httpClient.get(url, { params: queryParams }).subscribe(
        (res: any) => {
          console.log('接口获取成功', res);
          if (res.code === 200) {
            this.listOfData = res.result.data;
          }
        },
        (err) => {
          console.log('接口获取失败', err);
        }
      );
    }, time);
  }

  // 相关代码——进行网络请求
  getSwitchMapData() {
    let url = 'http://localhost:8080/api/mockDataNodePaging';
    let queryParams = new HttpParams();
    Object.keys(this.params).forEach((key) => {
      queryParams = queryParams.append(key, this.params[key]);
    });
    const params = {
      params: queryParams
    };
    // 取消之前的订阅（如果存在）
    this.unsubscribeSearch();
    this.searchSubscription = this.searchTerms
      .pipe(switchMap((params) => this.httpClient.get(url, params)))
      .subscribe(
        (res: any) => {
          this.listOfData = res.result.data;
        },
        (error) => {
          console.log('获取模板列表失败');
        }
      );
    this.searchTerms.next(params);
  }

  // 相关代码——取消订阅
  unsubscribeSearch(): void {
    if (this.searchSubscription) {
      this.searchSubscription.unsubscribe();
      this.searchSubscription = undefined;
    }
  }

  changePage() {
    this.params.page = this.params.page + 1;
  }

  resetPage() {
    this.params.page = 0;
  }
}
